package com.huida.app.jackson.usage;

/**
 * @Description:
 * @Author: Wangzz
 * @Version: 1.0.0
 * @CreateDate: Created in 2021/11/7 20:45
 * @UpdateDate: [dateFormat:YYYY-MM-DD][modifier][description]
 */

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashMap;

/**
 * 创建要给Student类，将创建一个JSON字符串学生的详细信息将其反序列化为学生的对象，然后将其序列化到JSON字符串
 *
 * JSON字符串 ===》 Java对象 ===》JSON字符串
 * */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
class Student{
    private String name;
    private Integer age;
}
public class JacksonTester {
    public static void main(String[] args) {
       test03();
    }

    public static void test03(){
        ObjectMapper om = new ObjectMapper();
        HashMap<String, Object> stuDataMap = new HashMap<>(); // Java Map Data

        // Java Array
        int[] marks = {1, 2, 3};
        // Java Object
        Student stu = Student.builder()
                .name("Wangzz")
                .age(22)
                .build();
        // Java String
        String info = "一名光荣的共青团员！";
        // Java Boolean
        Boolean status = true;
        // Java Double
        Double salary = 8888.8888;

        stuDataMap.put("marks", marks);
        stuDataMap.put("student", stu);
        stuDataMap.put("info", info);
        stuDataMap.put("status", status);
        stuDataMap.put("salary", salary);

        try {
            String jsonStr = om.writeValueAsString(stuDataMap);
            System.out.println(jsonStr);
/*
{
    "student": {
        "name": "Wangzz",
        "age": 22
    },
    "marks": [
        1,
        2,
        3
    ],
    "salary": 8888.8888,
    "info": "一名光荣的共青团员！",
    "status": true
}
*/
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public static void test02(){
        ObjectMapper om = new ObjectMapper();
        Student stu = Student.builder()
                .name("wangzz-felix")
                .age(22)
                .build();
        // Map the Java object to Json String
        try {
            String info = om.writeValueAsString(stu);
            System.out.println(info);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


    }

    public static void test01(){
        ObjectMapper om = new ObjectMapper();
        String jsonStr = "{\n" +
                "    \"name\": \"Mahesh\",\n" +
                "    \"age\": 21\n" +
                "}";
        // Map the jsonStr to Student
        try {
            Student student = om.readValue(jsonStr, Student.class);
            System.out.println(student);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }


}
